using System;
using System.Text;

namespace Glpt.Data
{
    /// <summary>
    /// 字符串加密方法类
    /// </summary>
    public class CharCrypto
    {
        private string leftChar = "";
        private string rightChar = "";
        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        public CharCrypto()
        {
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="param1">参数1</param>
        /// <param name="param2">参数2</param>
        public void Init(string param1, string param2)
        {
            leftChar = param1;
            rightChar = param2;
        }

        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="txt">要加密的字符串</param>
        /// <returns>加密后字符串</returns>
        public String Encrypt(String txt)
        {
            return leftChar + Convert.ToBase64String(DataFuns.DefaultEncoding.GetBytes(txt)).Replace("+", "%2B") + rightChar;
        }
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="txt">要解密的字符串</param>
        /// <returns>解密后字符串</returns>
        public String Decrypt(String txt)
        {
            txt = txt.Replace("%2B", "+");
            if (leftChar.Length > 0 && txt.StartsWith(leftChar))
                txt = txt.Substring(leftChar.Length);
            if (rightChar.Length > 0 && txt.EndsWith(rightChar))
                txt = txt.Substring(0, txt.Length - rightChar.Length);
            return DataFuns.DefaultEncoding.GetString(Convert.FromBase64String(txt));
        }
    }
}
